package service

import (
	"context"
	"errors"
	"github.com/wonderivan/logger"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"time"
)

var Node node

type node struct{}

type NodesResp struct {
	Items []corev1.Node `json:"items"`
	Total int           `json:"total"`
}

func (n *node) GetNodes(filterName string, limit, page int) (nodesResp *NodesResp, err error) {
	nodesList, err := K8s.ClientSet.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{})
	if err != nil {
		logger.Error(errors.New("获取nodes列表失败" + err.Error()))
		return nil, errors.New("获取nodes列表失败" + err.Error())
	}
	// 将nodeList中的node列表（Items），放进dataselector对象中，进行排序
	selectableData := &dataSelector{
		GenericDataList: n.toCells(nodesList.Items),
		DataSelect: &DataSelectQuery{
			Filter: &FilterQuery{Name: filterName},
			Paginate: &PaginateQuery{
				Limit: limit,
				Page:  page,
			},
		},
	}
	filtered := selectableData.Filter()
	total := len(filtered.GenericDataList)
	data := filtered.Sort().Paginate()

	nodes := n.fromCells(data.GenericDataList)

	return &NodesResp{
		Items: nodes,
		Total: total,
	}, nil
}

func (n *node) GetNodeDetail(nodename string) (nodedetail *corev1.Node, err error) {
	nodedetail, err = K8s.ClientSet.CoreV1().Nodes().Get(context.TODO(), nodename, metav1.GetOptions{})
	if err != nil {
		logger.Error(errors.New("获取node详情失败," + err.Error()))
		return nil, errors.New("获取node详情失败," + err.Error())
	}
	return nodedetail, nil
}

type nodeCell corev1.Node

func (n *node) toCells(node []corev1.Node) []DataCell {
	cells := make([]DataCell, len(node))
	for i := range node {
		cells[i] = nodeCell(node[i])
	}
	return cells
}
func (n *node) fromCells(cells []DataCell) []corev1.Node {
	nodes := make([]corev1.Node, len(cells))
	for i := range cells {
		nodes[i] = corev1.Node(cells[i].(nodeCell))
	}
	return nodes
}

func (n nodeCell) GetCreation() time.Time {
	return n.CreationTimestamp.Time
}

func (n nodeCell) GetName() string {
	return n.Name
}
